import React, { useEffect, useState, useRef } from 'react';
import { connect } from 'react-redux';
import PlusOutlined from '@ant-design/icons/PlusOutlined';
import { Image, Upload, type UploadProps } from 'antd';
import { setOssParams } from '@/redux/modules/global/action';
import { getOssParams } from '@/api/modules/common';
import axios from 'axios';

import './index.less';

const { Dragger } = Upload;

const Comp: React.FC = (props: any) => {
	const uploadRef: any = useRef();
	const { defaultValue, onChange, ossParams } = props;
	const [previewOpen, setPreviewOpen] = useState(false);
  	const [previewImage, setPreviewImage] = useState('');
	const [fileList, setFileList] = useState([]);
	const [fcous, setFcous] = useState(false);

	const getBase64 = (file: any) =>
		new Promise((resolve, reject) => {
		  const reader = new FileReader();
		  reader.readAsDataURL(file);
		  reader.onload = () => resolve(reader.result as string);
		  reader.onerror = (error) => reject(error);
		});
	const handlePreview = async (file: any) => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj);
		}

		setPreviewImage(file.url || (file.preview as string));
		setPreviewOpen(true);
	};
	
	const handleChange = ({ fileList: newFileList }: any) => {
		const formatFiles = newFileList.map((file: any) => {
			if (file.response  && file.response.data && file.response.data.data) {
				file.url = file.response.data.data.filename;
			}
			return file;
		});
		onChange(formatFiles);
		setFileList(formatFiles);
	};

	const onFcous = (e: any) => {
		const doms: any = document.querySelectorAll('.global-switch');
		for (let i = 0; i < doms.length; i++) {
			doms[i].click();
		}
		setTimeout(() => setFcous(true), 0)
		return e.stopPropagation();
	};
	const onUnFocus = (e: any) => {
		setFcous(false);
		return e.stopPropagation();
	};
	
	const CompProps: UploadProps = {
		method: 'post',
		name: 'file',
		fileList,
		multiple: true,
		listType: 'picture-card',
		style: { width: '102px' },
		customRequest: async (opt: any) => {
			const { file } = opt;
			const uploadParams = new FormData();
			const image_type = file.type.split("/")[1];
			const fKey = ossParams.dir + "/" + file.uid + "." + image_type;
			for (let key in ossParams) {
				uploadParams.append(key, ossParams[key]);
			}
			uploadParams.append('key', fKey);
			uploadParams.append('file', file);
			const data = await axios({
				url: ossParams.host,
				method: 'post',
				data: uploadParams,
			});
			opt.onSuccess(data, data);
		},
		onPreview: handlePreview,
		onChange: handleChange,
		onDrop(e) {
			console.log('Dropped files', e.dataTransfer.files);
		},
	};
	  
	const uploadButton = (
		<button style={{ border: 0, background: 'none', cursor: 'pointer'  }} type="button">
			<PlusOutlined />
			<div style={{ marginTop: 8 }}>上传图片</div>
			{ fcous ? '' : <div onClick={onFcous} className="cover" /> }
			<div className="global-switch" onClick={onUnFocus} />
		</button>
	);

	const getOssParamsFunc = async () => {
		try {
			const { data } = await getOssParams();
			props.setOssParams(data);
		} catch (error) {
			console.log(error, '获取oss参数失败');
		}
	};

	useEffect(() => {
		getOssParamsFunc();
	}, []);
	useEffect(() => {
		if (defaultValue && defaultValue.length) {
			setFileList(defaultValue);
			onChange(defaultValue);
		} else {
			setFileList([]);
		}
	}, [defaultValue]);
	useEffect(() => {
		if (fcous === true) {
			document.onpaste = (event: any) => {
				const files = event.clipboardData && event.clipboardData.files[0];
				if (files) {
					uploadRef.current.upload.uploader.uploadFiles([files]);
				}
			};
		} else {
			document.onpaste = null;
		}
	}, [fcous]);

	return (
		<div className={`wjj-upload ${fcous ? 'fcous' : ''}`}>
			<Dragger ref={uploadRef} height={102} {...CompProps}>
				{uploadButton}
			</Dragger>

			{previewImage && (
				<Image
					wrapperStyle={{ display: 'none' }}
					preview={{
						visible: previewOpen,
						onVisibleChange: (visible) => setPreviewOpen(visible),
						afterOpenChange: (visible) => !visible && setPreviewImage(''),
					}}
					src={previewImage}
				/>
			)}
		</div>
	);
};

const mapStateToProps = (state: any) => state.global;
const mapDispatchToProps = { setOssParams };
export default connect(mapStateToProps, mapDispatchToProps)(Comp);
